﻿using AutoMapper;
using gt.UserInfo.DomainModels.Abstractions;
using gt.UserInfo.DomainModels.Entity;
using gt.UserInfo.DomainModels.Respository;
using gt.UserInfo.DomainModels.ViewObject;
using NLog.Web.LayoutRenderers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace gt.UserInfo.DomainServices
{
    public class UserDomainService : IUserDomainService
    {
        private readonly IMapper _mapper;
        private readonly IUserRepository _userRepository;

        public UserDomainService(IMapper mapper, IUserRepository userRepository)
        {
            _mapper = mapper;
            _userRepository = userRepository;
        }

        public async Task<UserVO> LoginAsync(string name, string password)
        {
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password)) throw new ArgumentNullException();
            var entity = await _userRepository.GetUserAsync(name, password);
            if (entity == null) throw new InvalidOperationException("invalid user name or password.");
            return _mapper.Map<UserVO>(entity);
        }

        public async Task<int> RegisterAsync(UserVO user)
        {
            if (string.IsNullOrEmpty(user.Password)
                || string.IsNullOrEmpty(user.Phone)
                || string.IsNullOrEmpty(user.Name)
                || string.IsNullOrEmpty(user.ShowName)) throw new ArgumentNullException();

            var entity = _mapper.Map<UserEntity>(user);
            entity.CreateTime = DateTime.Now;

            var userId = await _userRepository.CreateAsync(entity);
            return userId;
        }
    }
}
